package com.gin.kotlin.no_gay_alliance.argument

import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.util.regex.Pattern

/**
 * 回复列表参数
 * @property type 类型
 * @property topicId 主题ID
 * @property page 页数
 * @property userId 用户ID（只看TA功能）
 * @property replyId 回复ID（单回复模式或回复列表滚动目标）
 * @property title 临时标题
 * @property totalPage 临时总页数
 * @property total 临时总楼层数
 * @property html 是否使用html方式请求
 * @property targetPage 如果指定，则翻页到该页 ,可以填写大于实际页数的整数，以跳转到最后一页
 * @property targetFloor 如果指定，则翻页到目标页后, 滚动到指定楼层
 * @property backupId 回复历史的ID，仅在 type = HISTORY使用
 * @property hostId 楼主ID，由外部传入
 * @constructor
 */
@Parcelize
data class ReplyListArgument(
    val type: Type,
    val topicId: Long? = null,
    val page: Int? = null,
    val userId: Long? = null,
    val replyId: Long? = null,
    val title: String? = null,
    val totalPage: Int? = null,
    val total: Int? = null,
    val html: Boolean = false,
    val targetPage: Int? = null,
    val targetFloor: Int? = null,
    val backupId: Long? = null,
    val hostId: String? = null,
) : Parcelable {

    /**
     * 请求类型
     */
    enum class Type {
        /**
         * 回复列表
         */
        LIST,

        /**
         * 单个回复
         */
        SINGLE,

        /**
         * 回复历史
         */
        HISTORY,
    }

    companion object {
        /**
         * 最大页
         */
        const val MAX_PAGE = 12751
        private val PID_PATTERN = Pattern.compile("#pid(\\d+)Anchor")

        /**
         * 从url中解析参数
         * @param url String?
         * @return ReplyListArgument?
         */
        fun parseUrl(url: String?): ReplyListArgument? {
            val httpUrl = url?.toHttpUrl() ?: return null

            val topicId = httpUrl.queryParameter("tid")?.toLong()
            // 页数 ，非空时如果为纯数字则直接使用，否则使用最大页
            val targetPage = httpUrl.queryParameter("page")?.let { it.toIntOrNull() ?: MAX_PAGE }
            val userId = httpUrl.queryParameter("authorid")?.toLong()
            val backupId = httpUrl.queryParameter("view_edit_bakup")?.toLong()
            val replyId = httpUrl.queryParameter("pid")?.toLong() ?: PID_PATTERN.matcher(url).takeIf { it.find() }?.group(1)?.toLong()
            val to = httpUrl.queryParameter("to")


            val type = when {
                // 跳转到指定页并滚动
                backupId != null -> Type.HISTORY
                replyId != null && topicId != null && targetPage != null -> Type.LIST
                replyId != null && to == null -> Type.SINGLE
                else -> Type.LIST
            }

            return ReplyListArgument(type, topicId, null, userId, replyId, null, targetPage = targetPage, backupId = backupId)
        }
    }
}